// H5 plus事件处理
var timeZs;
function plusReady(){
// 设置系统状态栏背景为灰色
	plus.navigator.setStatusBarBackground('#878d9d');
}
if(window.plus){
	plusReady();
}else{
	document.addEventListener('plusready', plusReady, false);
}
jQuery(document).ready(function() {
	var num = 1 / window.devicePixelRatio;
	var fontSize = document.documentElement.clientWidth / 10;
	document.getElementsByTagName('html')[0].style.fontSize = fontSize + 'px';
});
var socktListData;
var mask=mui.createMask();
var mstcok = function() {
	return {
		tabBarFun: function(page) {
			mui(".mui-bar").on('tap', '.mui-tab-item ',function() {
				var _page = this.getAttribute("data-page");
				var _url;
				switch(_page) {
					case 'marketPage':
						mui.openWindow({
							url: 'market.html'
						});
						break;
					case 'optionalPage':
						mui.plusReady(function() {
					        var list = plus.webview.getWebviewById('optional.html');
							mui.fire(list,'refresh');
						})
						mui.openWindow({
							url: 'optional.html'
						});
						break;
					case 'newsPage':
						mui.openWindow({
							url: 'news.html'
						});
						break;
					case 'tradePage':
						if(account&&account!=''){
							mui.openWindow({
								url: 'deal.html'
							});
						}else{
							mui.openWindow({
								url: 'login.html'
							});
						}
						break;
					case 'centerPage':
						if(account&&account!=''){
							mui.openWindow({
								url: 'users.html'
							});
						}else{
							mui.openWindow({
								url: 'login.html'
							});
						}
						break;
				}
			})
		},
		stockInfo:function(code,type){
			var minuteArr;
			var myChart = echarts.init(document.getElementById('barChart'));
			var valuesData,maData5,maData10,maData20,_end,_start;
			var orgData = {};
			var host = server.stockMinute+code;
			var upColor = '#f7474b';
			var downColor = '#40d034';
			dataRequest(host,0,100);
			mui(".tabState").on('tap','.mui-control-item',function(){
				//var timer;
				maskShowEvent();
				var _state = this.getAttribute("data-state");
				switch (_state){
					case 'minute':
						host = server.stockMinute+code;
						timer = setInterval(dataRequest,2000);
						_start = 0;
						_end = 100;
						break;
					case 'day':
						host = server.stockDay+code;
						clearInterval(timer);
						_start = 89;
						_end = 100;
						break;
					case 'week':
						host = server.stockWeek+code;
						clearInterval(timer);
						_start = 78;
						_end = 100;
						break;
					case 'month':
						host = server.stockMonth+code;
						clearInterval(timer);
						_start =0;
						_end = 100;
						break;
				}
				dataRequest(host,_start,_end);
			}) 
			function dataRequest(host,_start,_end){
				host = host||server.stockMinute+code;
				_start = _start||0;
				_end = _end||100;
				console.log(host);
				console.log(_start);
				console.log(_end);
				mui.ajax(host,{
					data:{},
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					headers:{'Content-Type':'application/json'},	              
					success:function(result){
						var data = result.data;
						//服务器返回响应，根据响应结果，分析是否登录成功；
						console.log(data);
						resultDeal(data,_start,_end);		
					},
					error:function(xhr,type,errorThrown){
						//异常处理；
						console.log(type);
					}
				});
			}
		    function resultDeal(rawData,_start,_end){
		    	var data = splitData(rawData);
		    	console.log(data);
		    	valuesData = data.values;
		    	maData5 = calculateMA(5, data);
		    	maData10 = calculateMA(10, data);
		    	maData20 = calculateMA(20, data);
		    	var _state = jQuery('.tabState .mui-active').attr('data-state');
		    	if(_state=='minute'){
		    		valuesData = '';
		    		maData5 = calcluateMinute(data);
		    		maData10 = '';
		    		maData20 = '';
		    	}
			    myChart.setOption(option = {
			        backgroundColor: '#232527',
			        animation: false,
			        legend: {
			            top: 10,
			            left: 'left',
			            data: ['MA5', 'MA10', 'MA20'],
			            itemWidth:5,  
		    			itemHeight:3, 
			            textStyle:{    
					        color:'#999',
					        fontSize:10
					    }
			        },
			        tooltip: {
			         //   trigger: 'axis',
			            axisPointer: {
			                type: 'cross'
			            },
			            backgroundColor: '#12253e',
			            borderWidth: 1,
			            borderColor: '#595a5b',
			            padding: 10,
			            textStyle: {
			                color: '#fff',
			                fontSize:10
			            },
			            position: function (pos, params, el, elRect, size) {
			                var obj = {top: 10};
			                obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
			                return obj;
			            }
			        },
			        axisPointer: {
			            link: {xAxisIndex: 'all'},
			            label: {
			                backgroundColor: '#12253e'
			            }
			        },
			        visualMap: {
			            show: false,
			            seriesIndex: 5,
			            dimension: 2,
			            pieces: [{
			                value: 1,
			                color: downColor
			            }, {
			                value: -1,
			                color: upColor
			            },{
			                value: 0,
			                color: '#d4d507'
			            }]
			        },
			        grid: [
			            {
			                left: '15%',
			                right: '5%',
			                top: '15%',
			                height: '50%'
			            },
			            {
			            	left: '15%',
			                right: '5%',
			                top: '80%',
			                height: '20%'
			            }
			        ],
			        xAxis: [
			            {
			                type: 'category',
			                data: data.categoryData,
			                scale: true,
			                boundaryGap : false,
			                axisLine: {onZero: false},
			                splitLine: {show: false},
			                splitNumber: 20,
			                min: 'dataMin',
			                max: 'dataMax',
			                axisPointer: {
			                    z: 100
			                },
			                axisLine:{  
			                    lineStyle:{  
			                        color:'#595a5b',  
			                        width:1,//这里是为了突出显示加上的  
			                    }  
			                } 
			            },
			            {
			                type: 'category',
			                gridIndex: 1,
			                data: data.categoryData,
			                scale: true,
			                boundaryGap : false,
			                axisLine: {onZero: false},
			                axisTick: {show: false},
			                splitLine: {show: false},
			                axisLabel: {show: false},
			                splitNumber: 20,
			                min: 'dataMin',
			                max: 'dataMax',
			                axisLine:{  
			                    lineStyle:{  
			                        color:'#595a5b',  
			                        width:1,//这里是为了突出显示加上的  
			                    }  
			                } 
			            }, 
			        ],
			        yAxis: [
			            {
			                scale: true,
			                splitArea: {
			                    show: false
			                },
			                axisLine:{  
			                    lineStyle:{  
			                        color:'#595a5b',  
			                        width:1,//这里是为了突出显示加上的  
			                    }  
			                },
			                splitLine: {show: false}
			            },
			            {
			                scale: false,
			                gridIndex: 1,
			                splitNumber:1,
			                axisLabel: {show: false},
			                axisLine: {show: false},
			                axisTick: {show: false},
			                splitLine: {show: false},
			            }
			        ],
			        dataZoom: [
			            {
			                type: 'inside',
			                xAxisIndex: [0, 1],
			                start: _start,
			                end: _end
			            },
			            {
			                show: false,
			                xAxisIndex: [0, 1],
			                type: 'slider',
			                top: '85%',
			                start: _start,
			                end: _end
			            }
			        ],
			        series: seriesData(data)
			    }, true);
			    maskHideEvent()
		    }
			function splitData(rawData) {			
				var _state = jQuery('.tabState .mui-active').attr('data-state');
				if(_state=='minute'){
					rawData = rawData.reverse();
				}
			    var categoryData = [];
			    var values = [];
			    var volumes = [];
			    var len = rawData.length;
			    for (var i = 0; i <rawData.length; i++) {
			    	categoryData.push(rawData[i].date);
			        var _open = Number(rawData[i].openPrice);
			        var _close = Number(rawData[i].closePrice);
			        var _low = Number(rawData[i].low);
			        var _high = Number(rawData[i].high);
			        var _volume = Number(rawData[i].volume);
			        values.push([_open,_close,_low,_high,_volume]);
			        if(_state=='minute'){
			        	if(i==0){
			        		volumes.push([i, _volume, 0]);
			        	}else{
			        		var state = _volume-Number(rawData[i-1].volume);
			        		volumes.push([i, state<=0 ? 0 : state, 0]);
			        	}
			        }else{
				        var state =  Number(rawData[i].openPrice)-Number(rawData[i].closePrice);
				        volumes.push([i, rawData[i].volume, state>=0 ? 1 : -1]);
			        }
			    }
			    var returnObj;
			    var timeLen = type==3?timeUs.length:timeHk.length;
			    if(_state=='minute'){
				    for(var n=len;n<timeLen;n++){
		    			values.push([]);
			   			volumes.push([n,'','']);
		    		}
				    var timeArr =  type==3?timeUs:timeHk;
			    	returnObj = {
				        categoryData:timeArr,
				        values: values,
				        volumes: volumes
				    }
			    }else{
			    	returnObj = {
				        categoryData: categoryData,
				        values: values,
				        volumes: volumes
				    }
			    	var _ma5 = calculateMAOrg(5, returnObj.values);
			    	var _ma10 = calculateMAOrg(10, returnObj.values);
			    	var _ma20 = calculateMAOrg(20, returnObj.values);
			    	for(var i=0;i<returnObj.values.length;i++){
			    		returnObj.values[i].push(_ma5[i],_ma10[i],_ma20[i])
			    	}
			    }
			    return returnObj;
			}
			function calculateMAOrg(dayCount, data) {
			    var result = [];
			    for (var i = 0, len = data.length; i < len; i++) {
			        if (i < dayCount) {
			            result.push('-');
			            continue;
			        }
			        var sum = 0;
			        for (var j = 0; j < dayCount; j++) {
			            sum += data[i - j][1];
			        }
			        result.push(+(sum / dayCount).toFixed(3));
			    }
			    return result;
			}
			function calculateMA(dayCount, data) {
			    var result = [];
			    for (var i = 0, len = data.values.length; i < len; i++) {
			        if (i < dayCount) {
			            result.push('-');
			            continue;
			        }
			        var sum = 0;
			        for (var j = 0; j < dayCount; j++) {
			            sum += data.values[i - j][1];
			        }
			        result.push(+(sum / dayCount).toFixed(3));
			    }
			    return result;
			}
			function calcluateMinute(data){
				var val = [],upDown = [],percent = [],volume = [];
				var closePrice = Number($('.closeCur').html());
			    for (var i = 0; i < data.values.length; i++) {
			        val.push(data.values[i][1]);
			        var _updown = (data.values[i][2] - closePrice).toFixed(2);
			        var _percent =((data.values[i][2] - closePrice)*100/closePrice).toFixed(2);
			        upDown.push(_updown);
			        percent.push(_percent);
			        volume.push(data.volumes[i][1]);
			    }
			    minuteArr = {
			    	time:data.categoryData,
			    	price:val,
			    	upDown:upDown,
			    	percent:percent,
			    	volume:volume
			    }
			    return val;
			}
			function calcluateUpDown(data){
				var result = [];
			    for (var i = 0, len = data.values.length; i < len; i++) {
			        result.push(data.values[i][1]);
			    }
			    return result;
			}
			function calcluatePercent(data){
				var result = [];
			    for (var i = 0, len = data.values.length; i < len; i++) {
			        result.push(data.values[i][1]);
			    }
			    return result;
			}
			function seriesData(data){
				console.log(data);
		    	var _state = jQuery('.tabState .mui-active').attr('data-state');
		    	var arr;
		    	if(_state=='minute'){
		    		arr = [
			            {
			                name: '',
			                type: 'candlestick',
			                data:  '',
			                itemStyle: {
			                    normal: {
			                        color: upColor,
			                        color0: downColor,
			                        borderColor: null,
			                        borderColor0: null
			                    }
			                }
			            },
			            {
			                name: '价格',
			                trigger: 'item',
			                type: 'line',
//			                symbol:'none',
//			                symbolOffset: ['50%','50%'],
			                data:calcluateMinute(data),
			                smooth: true,
			                tooltip: {
			                    formatter: function (param) {
			                    	var ind = param.dataIndex;
			                    	//昨日收盘价
			                    	var closePrice = Number($('.closeCur').html());
			                    	var percent = Number(minuteArr.percent[ind]);//幅度 
			                    	var upDown = Number(minuteArr.upDown[ind]);//涨跌
			                    	var priceDom = '',upDom = '', percentDom='';
			                    	//价格  
			                    	if(param.data > closePrice){
			                    		priceDom = '<span style="color:'+upColor+'">'+param.data+'</span>'
			                    	}else if(param.data < closePrice){
			                    		priceDom = '<span style="color:'+downColor+'">'+param.data+'</span>'
			                    	}else{
			                    		priceDom = '<span style="color:#fff">'+param.data+'</span>'
			                    	}
			                    	//涨跌
			                    	if(upDown > 0){
			                    		upDom = '<span style="color:'+upColor+'">'+upDown+'</span>'
			                    	}else if(upDown < 0){
			                    		upDom = '<span style="color:'+downColor+'">'+upDown+'</span>'
			                    	}else{
			                    		upDom = '<span style="color:#fff">'+upDown+'</span>'
			                    	}
			                    	//幅度
			                    	if(percent > 0){
			                    		percentDom = '<span style="color:'+upColor+'">'+percent+'%</span>'
			                    	}else if(upDown < 0){
			                    		percentDom = '<span style="color:'+downColor+'">'+percent+'%</span>'
			                    	}else{
			                    		percentDom = '<span style="color:#fff">'+percent+'%</span>'
			                    	}
			                    	//交易量
			                    	minuteArr.volume[ind] = (minuteArr.volume[ind]>=100000)?(minuteArr.volume[ind]/10000).toFixed(2)+'万':minuteArr.volume[ind];
			                        return [
			                            '<span style="text-align:center;margin-bottom:3px;">' + minuteArr.time[ind] + '</span><br/>',
			                            '价格: ' + priceDom + '<br/>',
			                            '涨跌: ' + upDom + '<br/>',
			                            '幅度: ' + percentDom + '<br/>',
			                            '成交: <span style="color:#f3f301;">'+minuteArr.volume[ind]+'</span>'
			                        ].join('');
			                    }
			                },
			                lineStyle: {
			                    normal: {
			                    	width:1,
			                    	opacity:1
			                    }
			                },
			                areaStyle: {
				                normal: {
				                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
				                        offset: 0,
				                        color: 'rgba(47, 132, 204,0.2)'
				                    }])
				                }
				            },
			                itemStyle: {
			                    normal: {
			                        color: '#c0c0c1'
			                    }
			                }
			            },
			            {
			                name: '涨跌',
			                type: 'line',
			                data:'',
			                smooth: true,
			                lineStyle: {
			                    normal: {opacity: 1}
			                },
			                itemStyle: {
			                    normal: {
			                        color: '#f3f301'
			                    }
			                }
			            },
			            {
			                name: '幅度',
			                type: 'line',
			                data: '',
			                smooth: true,
			                lineStyle: {
			                    normal: {opacity:1}
			                },
			                itemStyle: {
			                    normal: {
			                        color: '#7bbce9'
			                    }
			                }
			            },
			            {
			                name: '',
			                type: 'line',
			                data: '',
			                smooth: true,
			                lineStyle: {
			                    normal: {opacity: 1}
			                },
			                itemStyle:{
			                    normal:{
			                        color:'transparent',
			                        label : {
			                            show:false,
			                            color:'white',
			                            fontSize:'12'
			                        }
			                    }
		                	}
			            },
			            {
			                name: '成交量',
			                type: 'bar',
			                xAxisIndex: 1,
			                yAxisIndex: 1,
			                data: data.volumes
			            }
			        ]
		    	}else{
		    		arr = [
			            {
			                name: '',
			                trigger: 'item',
			                type: 'candlestick',
			                data:  data.values,
			                itemStyle: {
			                    normal: {
			                        color: upColor,
			                        color0: downColor,
			                        borderColor: null,
			                        borderColor0: null
			                    }
			                },
			                tooltip: {
			                    formatter: function (param) {
			                        return [
			                            '<span style="text-align:center;margin-bottom:3px;">' + param.name + '</span><br/>',
			                            '开盘: ' + param.data[1] + '<br/>',
			                            '最高: ' + getColor(param.data[4],param.data[1]) + '<br/>',
			                            '最低: ' + getColor(param.data[3],param.data[1]) + '<br/>',
			                            '收盘: ' + getColor(param.data[2],param.data[1]) + '<br/>',
			                            '涨跌幅: ' + upDown(param.data[1],param.data[2])+'<br/>',
			                            '成交量: <span style="color:#f3f301;">'+(param.data[5]/10000).toFixed(2)+'万</span></br>',
			                            'MA5: <span style="color:#980f9a;">' + param.data[6] +'</span><br/>',
			                            'MA10: <span style="color:#FFC938;">' + param.data[7] +'</span><br/>',
			                            'MA20: <span style="color:#7bbce9;">' + param.data[8] +'</span><br/>',
			                        ].join('');
			                    }
			                }
			            },
			            {
			                name: 'MA5',
			                type: 'line',
			                data:calculateMA(5, data),
			                smooth: true,
			                lineStyle: {
			                    normal: {opacity:1}
			                },
			                itemStyle: {
			                    normal: {
			                        color: '#980f9a'
			                    }
			                }
			            },
			            {
			                name: 'MA10',
			                type: 'line',
			                data: calculateMA(10, data),
			                smooth: true,
			                lineStyle: {
			                    normal: {opacity: 1}
			                },
			                itemStyle: {
			                    normal: {
			                        color: '#f3f301'
			                    }
			                }
			            },
			            {
			                name: 'MA20',
			                type: 'line',
			                data: calculateMA(20, data),
			                smooth: true,
			                lineStyle: {
			                    normal: {opacity:1}
			                },
			                itemStyle: {
			                    normal: {
			                        color: '#7bbce9'
			                    }
			                }
			            },
			            {
			                name: 'MA30',
			                type: 'line',
			                data: '',
			                smooth: true,
			                lineStyle: {
			                    normal: {opacity: 1}
			                },
			                itemStyle:{
			                    normal:{
			                        color:'transparent',
			                        label : {
			                            show:false,
			                            color:'white',
			                            fontSize:'12'
			                        }
			                    }
		                	}
			            },
			            {
			                name: 'Volume',
			                type: 'bar',
			                xAxisIndex: 1,
			                yAxisIndex: 1,
			                data: data.volumes
			            }
			        ]
		    	}
				return arr;
			}
			setTimeout(stockeve(),2000);
			var timer;
			function stockeve(){			
				var _state = jQuery('.tabState .mui-active').attr('data-state');
		    	if(_state=='minute'){
		    		timer = setInterval(dataRequest,2000);
		    	}else{
		    		return;
		    	}
			};
			function upDown(open,close){
				var rate = (open-close)*100/close;
				rate = rate.toFixed(2)
				var _html;
				if(rate < 0){
					_html = '<span style="color:#00da3c">'+ rate +'%</span>';
				}else if(rate > 0){
					_html = '<span style="color:#ec0000">'+ rate +'%</span>';
				}else{
					_html = '<span style="color:#fff">'+ rate +'%</span>';
				}
				return _html;
			}
			function getColor(data,openPrice){
				var dom = '';
				if(data > openPrice){
					dom = '<span style="color:#ec0000">'+data+'</span>';
				}else if(data < openPrice){
					dom = '<span style="color:#00da3c;;">'+data+'</span>';
				}else{
					dom = '<span style="color:#fff;">'+data+'</span>';
				}
				return dom;
			}
		},
		/*stockList:function(type){
			console.log(type);
			if(!type){
				type='hk'
			}
			mui.ajax(server.stockZS+type,{
				data:{},
				dataType:'json',//服务器返回json格式数据
				type:'post',//HTTP请求类型
				timeout:10000,//超时时间设置为10秒；
				headers:{'Content-Type':'application/json'},	              
				success:function(result){
					if(result.code==1){
						 mui.toast(result.msg); 
					}else {
						//股票指数等数据呈现
						var dataArr=[];
						jQuery.each(result.data,function(index,ele){
							var objData = JSON.parse(result.data[index]);
							objData.name = hexToDec(objData.name);
							var a = objData.changeRate.replace(/\%/g,'');
							objData.changeRate = Number(a);
							dataArr.push(objData);
						})
						jo.reTpl(jQuery('#tempZS'),{data:dataArr},jQuery('#contZS'));
						listDataRequest();
						setInterval(topZs,3000)
					}
				},
				error:function(xhr,type,errorThrown){
					//异常处理；
					console.log(type);
				}
			});
			//头部信息2s刷新
			function topZs(){
				var typeS = jQuery('.stockTab .stockActive').attr('data-type');
				mui.ajax(server.stockZS+typeS,{
					data:{},
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					headers:{'Content-Type':'application/json'},	              
					success:function(result){
						if(result.code==1){
							// mui.toast(result.msg); 
						}else {
							//股票指数等数据呈现
							var dataArr=[];
							jQuery.each(result.data,function(index,ele){
								var objData = JSON.parse(result.data[index]);
								objData.name = hexToDec(objData.name);
								var a = objData.changeRate.replace(/\%/g,'');
								objData.changeRate = Number(a);
								dataArr.push(objData);
							})
							jo.reTpl(jQuery('#tempZS'),{data:dataArr},jQuery('#contZS'));
						}
					},
					error:function(xhr,type,errorThrown){
						//异常处理；
						console.log(type);
					}
				});
			}
			//列表数据请求
			function listDataRequest(){
				mui.ajax(server.stockList+type,{
					data:{},
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					headers:{'Content-Type':'application/json'},	              
					success:function(result){
						if(result.code==1){
							 mui.toast(result.msg); 
						}else {
							dataShow(result.data);
						}
					},
					error:function(xhr,type,errorThrown){
						//异常处理；
						console.log(type);
					}
				});
			}
			//列表数据展示
			function dataShow(data){
				//美股  港股 按钮样式改变
				var ths = jQuery('.stockTab .stockActive');
				var _stockType = jQuery('.stockTab .stockActive').attr('data-type');
				if(_stockType != type){
					ths.removeClass('stockActive');
					ths.siblings().addClass('stockActive');
				}
				maskHideEvent();
				var dataArr=[];
				jQuery.each(data,function(index,ele){
					var objData = JSON.parse(data[index]);
					objData.name = hexToDec(objData.name);
					objData['stockType'] = type;
					dataArr.push(objData);
				})
				jo.reTpl(jQuery('#temp'),{data:dataArr},jQuery('#cont'));
				socktListData = dataArr;
				sockteRequest(type);
			}
			mui("#cont").on('tap','.mui-row',function(){
			    var code = this.getAttribute("data-code");
			    mui.openWindow({
			    	id:'stockInfo.html',
			    	url:'stockInfo.html?code='+code,
				    extras:{
				    	code:code
				    }
			  	});
			})
		},*/
		stockList:function(type){
			clearInterval(timeZs);
			var urlZs,urlList;
			switch(type){
				case 'hk':
					urlZs = server.stockZS+type;
					urlList = server.stockList+type;
					jQuery('.stockHk').addClass('stockActive').siblings().removeClass('stockActive');
					break;
				case 'us':
					urlZs = server.stockZS+type;
					urlList = server.stockList+type;
					jQuery('.stockUs').addClass('stockActive').siblings().removeClass('stockActive');
					break;
				case 'gd':
					urlZs = urlList = server.goodsList;
					jQuery('.stockGd').addClass('stockActive').siblings().removeClass('stockActive');
					break;
				default:
					urlZs = server.stockZS+type;
					urlList = server.stockList+type;
					break;
			}
			//指数数据
			mui.ajax(urlZs,{
				data:{},
				dataType:'json',//服务器返回json格式数据
				type:'post',//HTTP请求类型
				timeout:10000,//超时时间设置为10秒；
				headers:{'Content-Type':'application/json'},	              
				success:function(result){
					if(result.code==1){
						 mui.toast(result.msg); 
					}else {
						var dataArr=[];
						//股票指数等数据呈现、
						if(type=='gd'){
							var rdata = result.data;
							jQuery.each(rdata,function(index,ele){
								if(ele.code=='GC1802'||ele.code=='SI1803'||ele.code=='CL1801'){
									ele.name = hexToDec(ele.name);
									ele.closePrice = Number(ele.closePrice).toFixed(3);
									ele.price = Number(ele.price).toFixed(3);
									var a = ele.changeRate.replace(/\%/g,'');
									ele.changeRate = Number(a);
									dataArr.push(ele);
								}
							})
						}else{
							jQuery.each(result.data,function(index,ele){
//								var objData = JSON.parse(result.data[index]);
								var objData = result.data[index];
								objData.name = hexToDec(objData.name);
								objData.closePrice = Number(objData.closePrice).toFixed(3);
								objData.price = Number(objData.price).toFixed(3);
								var a = objData.changeRate.replace(/\%/g,'');
								objData.changeRate = Number(a);
								dataArr.push(objData);
							})
						}
						jo.reTpl(jQuery('#tempZS'),{data:dataArr},jQuery('#contZS'));
						listDataRequest();
						clearInterval(timeZs);
 						timeZs = setInterval(topZs,2000);
					}
				},
				error:function(xhr,type,errorThrown){
					//异常处理；
					console.log(type);
				}
			});
			//头部信息2s刷新
			function topZs(){
				var ths = jQuery('.stockTab .stockActive');
				switch(type){
					case 'hk':
						urlZs = server.stockZS+type;
						break;
					case 'us':
						urlZs = server.stockZS+type;
						break;
					case 'gd':
						urlZs =server.goodsList;
						break;
					default:
						break;
				}
				/*var typeS = jQuery('.stockTab .stockActive').attr('data-type');*/
				mui.ajax(urlZs,{
					data:{},
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					headers:{'Content-Type':'application/json'},	              
					success:function(result){
						if(result.code==1){
							// mui.toast(result.msg); 
						}else {
							var dataArr=[];
							//股票指数等数据呈现
							if(type=='gd'){
								jQuery.each(result.data,function(index,ele){
									if(ele.code=='GC1802'||ele.code=='SI1803'||ele.code=='CL1801'){
										ele.name = hexToDec(ele.name);
										var a = ele.changeRate.replace(/\%/g,'');
										ele.changeRate = Number(a);
										ele.closePrice = Number(ele.closePrice).toFixed(3);
										ele.price = Number(ele.price).toFixed(3);
										dataArr.push(ele);
									}
								})
							}else{
								jQuery.each(result.data,function(index,ele){
									var objData = result.data[index];
									objData.name = hexToDec(objData.name);
									var a = objData.changeRate.replace(/\%/g,'');
									objData.changeRate = Number(a);
									dataArr.push(objData);
								})
							}
//							console.log(dataArr);
							jo.reTpl(jQuery('#tempZS'),{data:dataArr},jQuery('#contZS'));
						}
					},
					error:function(xhr,type,errorThrown){
						//异常处理；
						console.log(type);
					}
				});  
			}
			//列表数据请求
			function listDataRequest(){
				mui.ajax(urlList,{
					data:{},
					dataType:'json',//服务器返回json格式数据
					type:'post',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；
					headers:{'Content-Type':'application/json'},	              
					success:function(result){
						console.log(result)
						if(result.code==1){
							 mui.toast(result.msg); 
						}else {
							dataShow(result.data);
						}
					},
					error:function(xhr,type,errorThrown){
						//异常处理；
						console.log(type);
					}
				});
			}
			//列表数据展示
			function dataShow(data){
				//美股  港股 按钮样式改变
				maskHideEvent();
				var dataArr=[];
				jQuery.each(data,function(index,ele){
					ele.name =  hexToDec(ele.name);
					ele['stockType'] = type;
					var objData = ele;
					ele.closePrice = Number(ele.closePrice).toFixed(3);
					ele.price = Number(ele.price).toFixed(3);
					var a =ele.changeRate.replace(/\%/g,'');
					ele.changeRate = Number(a);
					dataArr.push(ele);
				})
				jo.reTpl(jQuery('#temp'),{data:dataArr},jQuery('#cont'));
				socktListData = dataArr;
				sockteRequest(type);
			}
			mui("#cont").on('tap','.mui-row',function(){
			    var code = this.getAttribute("data-code");
			    mui.openWindow({
			    	id:'stockInfo.html',
			    	url:'stockInfo.html?code='+code,
				    extras:{
				    	code:code
				    }
			  	});
			})
		},
		optional:function(){
			var codeContainer;
			var data = {
				action:"optionalList",
				app:'app',
				account:account
			}
			ajaxEve(server.optSel,data,function(result){
				if(result.data.length>0){
					jQuery('.optionalEdit').show();
					codeContainer = result.data;
					jo.reTpl(jQuery('#temp'),{data:result.data},jQuery('#cont'));
					socketDataDeal(result.data);
					usual()
				}else{
//						mui.toast('还没有自选股票');
					jQuery('.optionalEdit').hide();
				}	
			})
			function usual(){
				mui('#cont').on('tap','.mui-row',function(){
					var _code = jQuery(this).attr('data-code');
					mui.openWindow({
						url: 'stockInfo.html?code='+_code
					});
				})
			}
			var codeString = '';
			function socketDataDeal(data){
				var codeArr = [];
				for(var i=0;i< data.length;i++){
					codeArr.push(data[i].code);
					if(i == data.length-1){
						codeString = codeString+data[i].code;
					}else{
						codeString = codeString+data[i].code+',';
					}
				}
				//stockInfoEve();
				setInterval(stockInfoEve,2000);
			}
			function stockInfoEve(){
				var data = {
					action:"oneStockInfo",
					app:'app',
					account:account,
					stockCode:codeString
				}
				jQuery.ajax({
					type:'post',
					url:server.optSel,
					data:data,
					success:function(result){
						if(result.code==1){
							 //mui.toast(result.msg); 
						}else {
							var data = result.data;
							for(var i = 0;i<data.length;i++){
								var iCode = data[i].code;
								var iPrice =Number(data[i].price);
								var iRate = Number(data[i].changeRate);		
								for(var j = 0; j< codeContainer.length;j++){
									var jCode = codeContainer[j].code;
									var jPrice = Number(codeContainer[j].price);
									if(iCode==jCode && iPrice != jPrice){
										codeContainer[j].price = iPrice;
										codeContainer[j].changeRate = iRate;
										document.getElementsByClassName(jCode+'price')[0].innerHTML = iPrice;
										document.getElementsByClassName(jCode+'rate')[0].innerHTML = iRate+'%';
										var dom = '.'+jCode+'price',domRate = '.'+jCode+'rate';
										if(iRate<0&&jQuery(domRate).hasClass('highpercent')){
											jQuery(domRate).addClass('lowpercent').removeClass('highpercent');
										}else if(iRate>=0&&jQuery(domRate).hasClass('lowpercent')){
											jQuery(domRate).removeClass('lowpercent').addClass('highpercent');
										}
										if(iPrice-jPrice>0){
											jQuery(dom).addClass('high-price');
											setTimeout("jQuery('"+dom+"').removeClass('high-price');",800);
										}else{
											jQuery(dom).addClass('low-price');
											setTimeout("jQuery('"+dom+"').removeClass('low-price');",800);
										}
									}
								}
							}
							//jo.reTpl(jQuery('#temp'),{data:codeContainer},jQuery('#cont'));
						}
					},
					error:function(e){
						console.log(e);
					}
				})
			}
		},
		optionalEdit:function(){
			var data = {
				action:"optionalList",
				app:'app',
				account:account
			};
			ajaxEve(server.optSel,data,function(result){
				if(result.data.length>0){
					jo.reTpl(jQuery('#temp'),{data:result.data},jQuery('#cont'));
					for(var i=0;i< result.data.length;i++){
						codeListArr.push(result.data[i].code);
					}
					console.log(codeListArr);
					usualDeal();
				}else{
					mui.toast('还没有自选股票')
				}	
			})
			function usualDeal(){
				//delete
				mui('.dealList').on('tap','.delOpt',function(){
					var ths =  jQuery(this);
					var _code =ths.attr('data-code');
					var data = {
						action:"delOptional",
						app:'app',
						account:account,
						stockCode:_code
					}
					ajaxEve(server.optSel,data,function(result){
						mui.toast(result.msg);
						ths.parents('.mui-row').remove();
						return;
					})
				})
				//top
				mui('.dealList').on('tap','.topOpt',function(){
					var ths = jQuery(this);
					var codeCur = ths.attr('data-code');
					var ind = jQuery.inArray(codeCur,codeListArr);
					codeListArr.splice(ind,1);
					codeListArr.splice(0,0,codeCur);
					var dom = ths.parents('.mui-row').html();
					ths.parents('.mui-row').remove();
					jQuery('#cont').prepend('<div class="mui-row">'+dom+'</div>')
				})
			}
		}
	}
}
//websocket
var websocket;
function sockteRequest(type){
	// 首先判断是否 支持 WebSocket
	if ('WebSocket' in window) {
		websocket = new WebSocket(server.sockteMoz+account);
	} else if ('MozWebSocket' in window) {
		websocket = new MozWebSocket(server.sockteWeb+account);
	} else {
		websocket = new SockJS(server.sockteJs+account);
	}
	// 打开时
	websocket.onopen = function(evnt) {
		console.log(" websocket.onopen  ");
		var msg;
		switch(type){
			case 'us':
				msg = {"type": "us_market_list"};
				break;
			case 'hk':
				msg = {"type": "hk_market_list"};
				break;
			case 'gd':
				msg = {"type": "goods_list"};
				break;
			case 'own':
				msg = {"type": "self_select","list":["00001","appl"]};
				break;
		}
		send(msg);
	};
	// 处理消息时
	websocket.onmessage = function(evnt) {
		console.log('websocket onmessage');
		socketCompare(evnt.data);
	};
	websocket.onerror = function(evnt) {
		console.log('websocket onerror');
	};
	websocket.onclose = function(evnt) {
		console.log("  websocket.onclose  ");
	};	
}
function send(msg){
	websocket.send(JSON.stringify(msg));
}
function socketCompare(data){
	var getData = JSON.parse(data);
	getData.name = hexToDec(getData.name);
	console.log(getData);
	var _icode = getData.code;
	var _iprice = getData.price;
	var _changeRate = getData.changeRate;
	for(var j=0;j<socktListData.length;j++){
		var _jcode = socktListData[j].code;
		var _jprice = socktListData[j].price;
		if(_icode == _jcode && _iprice!=_jprice){
			socktListData[j].price = Number(_iprice).toFixed(3);
			socktListData[j].changeRate = _changeRate;
			document.getElementsByClassName(_jcode+'price')[0].innerHTML = Number(_iprice).toFixed(3);
			_changeRate =Number(_changeRate.replace(/\%/,'')).toFixed(2)
			document.getElementsByClassName(_jcode+'rate')[0].innerHTML = _changeRate+'%';
			
			var dom = '.'+_jcode+'price',domRate = '.'+_jcode+'rate';
			if(_changeRate<0&&!jQuery(domRate).hasClass('lowpercent')){
				jQuery(domRate).addClass('lowpercent,equalpercent').removeClass('highpercent');
			}else if(_changeRate>0&&!jQuery(domRate).hasClass('highpercent')){
				jQuery(domRate).removeClass('lowpercent,equalpercent').addClass('highpercent');
			}else if(_changeRate==0&&!jQuery(domRate).hasClass('equalpercent')){
				jQuery(domRate).removeClass('lowpercent,highpercent').addClass('equalpercent');
			}
			if(_changeRate>0){
				jQuery(dom).addClass('high-price');
				setTimeout("jQuery('"+dom+"').removeClass('high-price');",800);
			}else if(_changeRate<0){
				jQuery(dom).addClass('low-price');
				setTimeout("jQuery('"+dom+"').removeClass('low-price');",800);
			}else{
				jQuery(dom).addClass('equal-price');
				setTimeout("jQuery('"+dom+"').removeClass('equal-price');",800);
			}
		}
	}
	//jo.reTpl(jQuery('#temp'),{data:socktListData},jQuery('#cont'));
}
//mask show
function maskShowEvent(){
	if(jQuery('.maskDiy').html()==undefined){
		jQuery('body').append('<div class="maskDiy"><div id="dcache"><span class="mui-spinner"></span></div></div>');
		return;
	}
}
//mask hide
function maskHideEvent(){
	var dom = jQuery('.maskDiy')
	if(jQuery('.maskDiy').html()!=undefined){
		jQuery('.maskDiy').remove();
	}
	return;
}
//Unicode 转换中文
function hexToDec(str) {
    str=str.replace(/\\/g,"%");
    return unescape(str);
}
function ajaxEve(url,data,success){
	jQuery.ajax({
		type:'post',
		url:url,
		data:data,
		beforeSend:function(){
			maskShowEvent();
		},
		success:function(result){
			//console.log(result);
			maskHideEvent();
			if(result.code==1){
				 mui.toast(result.msg); 
			}else {
				success(result);
			}
		},
		error:function(e){
			maskHideEvent();
			console.log(e);
		}
	})
}
